

package cn.shengchao.examstar.distributor.gateway.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.DesensitizedUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.shengchao.examstar.distribute.infrastrure.po.DistributeNodeInfo;
import cn.shengchao.examstar.distribute.infrastrure.po.DistributeNodeRoleChain;
import cn.shengchao.examstar.distribute.infrastrure.po.DistributeUserInvite;
import cn.shengchao.examstar.distribute.infrastrure.query.DistributeUserSaleDetailQuery;
import cn.shengchao.examstar.distribute.infrastrure.query.SaleAmountQuery;
import cn.shengchao.examstar.distribute.infrastrure.service.DistributeNodeInfoService;
import cn.shengchao.examstar.distribute.infrastrure.service.DistributeOrderTaskSaleService;
import cn.shengchao.examstar.distribute.infrastrure.service.DistributeUserInviteService;
import cn.shengchao.examstar.distribute.infrastrure.vo.DistributeOrder;
import cn.shengchao.examstar.distribute.infrastrure.vo.DistributeSale;
import cn.shengchao.examstar.distribute.model.DistributeNodeRoleChainExistModel;
import cn.shengchao.examstar.distribute.ohs.local.appservice.DistributeNodeRoleChainDomainService;
import cn.shengchao.examstar.distribute.ohs.local.appservice.DistributeNodeRoleChainExistLoader;
import cn.shengchao.examstar.distributor.gateway.controller.query.MemberPageQuery;
import cn.shengchao.examstar.distributor.gateway.controller.query.OrderPageQuery;
import cn.shengchao.examstar.distributor.gateway.controller.query.OrderQuery;
import cn.shengchao.examstar.distributor.gateway.controller.query.StudentPageQuery;
import cn.shengchao.examstar.distributor.gateway.service.message.*;
import cn.shengchao.examstar.pay.acl.ports.repositories.IOrderRepository;
import cn.shengchao.examstar.rpc.base.PageResult;
import cn.shengchao.examstar.rpc.distribute.enums.DistributeDataStatusEnum;
import cn.shengchao.examstar.rpc.distribute.enums.DistributeSaleRoleEnum;
import cn.shengchao.examstar.rpc.distribute.enums.DistributeTypeEnum;
import cn.shengchao.examstar.rpc.distribute.req.DistributeNodeInfoQueryPage;
import cn.shengchao.examstar.rpc.distribute.resp.DistributeNodeInfoRespEntity;
import cn.shengchao.examstar.rpc.orders.req.OrderQueryPage;
import cn.shengchao.examstar.rpc.orders.res.OrderList;
import cn.shengchao.examstar.rpc.uddsys.bi.PlatformUserArchBI;
import cn.shengchao.examstar.rpc.uddsys.req.DistributeNodeInfoStateReq;
import cn.shengchao.examstar.rpc.uddsys.req.DistributeUserInvitePageQuery;
import cn.shengchao.examstar.rpc.uddsys.resp.DistributeUserInviteVo;
import cn.shengchao.examstar.rpc.uddsys.resp.DistributeUserProfitDetailVo;
import cn.shengchao.examstart.user.acl.adapters.repositories.UserRepository;
import cn.shengchao.examstart.user.domain.entity.User;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

@Service
public class DistributorService {

    @Autowired
    private DistributeNodeInfoService distributeNodeInfoService;

    @Autowired
    private DistributeNodeRoleChainDomainService distributeNodeRoleChainDomainService;
    @Autowired
    private DistributeNodeRoleChainExistLoader distributeNodeRoleChainExistLoader;
    @Autowired
    private DistributeUserInviteService distributeUserInviteService;

    @Autowired
    private DistributeOrderTaskSaleService distributeOrderTaskSaleService;

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private IOrderRepository iOrderRepository;

    @Autowired
    private PlatformUserArchBI platformUserArchBI;

    /**
     * 首页数据展示
     */
    public DistributorIndexInfo getDistributorIndexInfo(Long userId) {
        DistributeNodeInfo distributeNodeInfo = distributeNodeInfoService.getNodeInfoForUser(userId, DistributeTypeEnum.TYPE_SALE);
        if (distributeNodeInfo == null) {
            return new DistributorIndexInfo();
        }
        //获取所有销售
        List<DistributeNodeRoleChain> sale = distributeNodeRoleChainDomainService.getAllSaleNodeId(distributeNodeInfo.getId());
        List<Long> userIds = new ArrayList<>();
        for (DistributeNodeRoleChain distributeNodeRoleChain : sale) {
            userIds.add(distributeNodeRoleChain.getRefUserId());
        }
        userIds.add(distributeNodeInfo.getUserId());
        //获取邀请的学员(上月1号到目前)
        Map<Long, List<DistributeUserInvite>> mapStudent = distributeUserInviteService.getInviteRecord(userIds, DateUtil
                .beginOfMonth(DateUtil.lastMonth()), new Date());
        Optional<List<DistributeUserInvite>> stduents = mapStudent.values().stream().reduce((a, b) -> {
            a.addAll(b);
            return a;
        });
        DistributorIndexInfo distributorIndexInfo = new DistributorIndexInfo();
        distributorIndexInfo.setId(distributeNodeInfo.getUserId());
        distributorIndexInfo.setFullName(distributeNodeInfo.getFullName());
        distributorIndexInfo.setHeadImageUrl(distributeNodeInfo.getHeadImageUrl());
        stduents.ifPresent(item -> {
            //获取本月的学员
            long count = item.stream()
                    .filter(invite -> DateUtil.isIn(new DateTime(invite.getCreateTime()), DateUtil
                            .beginOfMonth(new Date()), new Date()))
                    .map(DistributeUserInvite::getUserId)
                    .distinct()
                    .count();
            distributorIndexInfo.setThisMonthNewStudent((int) count);
            //上月的学员
            long lastMonthCount = item.stream()
                    .filter(invite -> DateUtil.isIn(new DateTime(invite.getCreateTime()), DateUtil.beginOfMonth(DateUtil
                            .lastMonth()), DateUtil.endOfMonth(DateUtil.lastMonth())))
                    .map(DistributeUserInvite::getUserId)
                    .distinct()
                    .count();
            distributorIndexInfo.setLastMonthNewStudent((int) lastMonthCount);
        });
        if (stduents.isEmpty()) {
            distributorIndexInfo.setThisMonthNewStudent(0);
            distributorIndexInfo.setLastMonthNewStudent(0);
        }
        SaleAmountQuery saleAmountQuery = new SaleAmountQuery();
        if (DistributeSaleRoleEnum.ROLE_DSPD_EMP.getCode().equals(distributeNodeInfo.getDistributeRoleCode()) ) {
            saleAmountQuery.setSaleUserId(distributeNodeInfo.getUserId());
            saleAmountQuery.setDistributeUserId(distributeNodeInfo.getAdminUserId());
        } else {
            saleAmountQuery.setDistributeUserId(distributeNodeInfo.getUserId());
        }
        saleAmountQuery.setStartSaleTime(DateUtil.beginOfMonth(new Date()));
        saleAmountQuery.setEndSaleTime(new Date());
        //本月收益
        DistributeSale distributeSale = distributeOrderTaskSaleService.getSaleAmount(saleAmountQuery);
        BigDecimal thisMonthCourseIncome = distributeSale.getAmount();
        if (thisMonthCourseIncome != null) {
            distributorIndexInfo.setThisMonthCourseIncome(thisMonthCourseIncome.setScale(2,  RoundingMode.HALF_UP));
        } else {
            distributorIndexInfo.setThisMonthCourseIncome(BigDecimal.ZERO);
        }

        saleAmountQuery = new SaleAmountQuery();
        if (DistributeSaleRoleEnum.ROLE_DSPD_EMP.getCode().equals(distributeNodeInfo.getDistributeRoleCode()) ) {
            saleAmountQuery.setSaleUserId(distributeNodeInfo.getUserId());
            saleAmountQuery.setDistributeUserId(distributeNodeInfo.getAdminUserId());
        } else {
            saleAmountQuery.setDistributeUserId(distributeNodeInfo.getUserId());
        }
        saleAmountQuery.setStartSaleTime(DateUtil.beginOfMonth(DateUtil.lastMonth()).toJdkDate());
        saleAmountQuery.setEndSaleTime(DateUtil.endOfMonth(DateUtil.lastMonth()).toJdkDate());
        //本月收益
        distributeSale = distributeOrderTaskSaleService.getSaleAmount(saleAmountQuery);
        BigDecimal lastMonthCourseIncome = distributeSale.getAmount();
        distributorIndexInfo.setLastMonthCourseIncome(lastMonthCourseIncome != null ? lastMonthCourseIncome.setScale(2, RoundingMode.HALF_UP) : BigDecimal.ZERO);
        if (distributeNodeInfo.getDistributeRoleCode().equals(DistributeSaleRoleEnum.ROLE_DSPD_EMP.getCode())){
            List<DistributeUserInvite> currentList = distributeUserInviteService.getInviteRecordListByDistributeUserIdsAndRole(List.of(distributeNodeInfo.getUserId()), DistributeSaleRoleEnum.ROLE_SLMB.getCode(),DateUtil.beginOfMonth(new Date()).toJdkDate(),
                    DateUtil.endOfMonth(new Date()).toJdkDate());
            List<DistributeUserInvite> lastList= distributeUserInviteService.getInviteRecordListByDistributeUserIdsAndRole(List.of(distributeNodeInfo.getUserId()), DistributeSaleRoleEnum.ROLE_SLMB.getCode(),DateUtil.beginOfMonth(DateUtil.lastMonth()).toJdkDate(),
                    DateUtil.endOfMonth(DateUtil.lastMonth()).toJdkDate());
            distributorIndexInfo.setLastMonthNewMember(CollUtil.isEmpty(lastList)?0:lastList.size());
            distributorIndexInfo.setThisMonthNewMember(CollUtil.isEmpty(currentList)?0:currentList.size());
        }else {
            long thisMonthNewMember = sale.stream().filter(item -> item.getRefRoleCode().equals(DistributeSaleRoleEnum.ROLE_SLMB.getCode()) &&
                    DateUtil.isIn(new DateTime(item.getCreateTime()), DateUtil.beginOfMonth(new Date()), new Date())).count();
            distributorIndexInfo.setThisMonthNewMember(Math.toIntExact(thisMonthNewMember));
            long lastMonthNewMember = sale.stream()
                    .filter(item -> item.getRefRoleCode().equals(DistributeSaleRoleEnum.ROLE_SLMB.getCode()) &&
                            DateUtil.isIn(new DateTime(item.getCreateTime()),
                                    DateUtil.beginOfMonth(DateUtil.lastMonth()),
                                    DateUtil.endOfMonth(DateUtil.lastMonth())))
                    .count();
            distributorIndexInfo.setLastMonthNewMember(Math.toIntExact(lastMonthNewMember));
        }
        return distributorIndexInfo;
    }

    /**
     * 业绩排行榜
     */
    public List<Rankings> getDistributorRanking(Long userId, Long type) {
        DistributeNodeInfo distributeNodeInfo = distributeNodeInfoService.getNodeInfoForUser(userId, DistributeTypeEnum.TYPE_SALE);
        if (distributeNodeInfo == null) {
            return List.of();
        }
        var ref = new Object() {
            List<Rankings> rankings = new ArrayList<>();
        };
        //获取所有销售
        List<DistributeNodeRoleChain> sale = distributeNodeRoleChainDomainService.getAllSaleNodeId(distributeNodeInfo.getId());
        List<Long> saleIds = new ArrayList<>(sale.stream().map(DistributeNodeRoleChain::getRefUserId).toList());
        saleIds.add(distributeNodeInfo.getUserId());
        if (type == 1) {
            Map<Long, Long> mapMember = distributeOrderTaskSaleService.
                    saleMemberSum(saleIds, DateUtil.beginOfMonth(new Date()), new Date());
            for (Long saleId : saleIds) {
                Rankings ranking = Rankings.builder().id(saleId)
                        .sum(Math.toIntExact(mapMember.getOrDefault(saleId, 0L))).build();
                ref.rankings.add(ranking);
            }
        } else {
            //获取所有的学员(本月新增)
            Map<Long, List<DistributeUserInvite>> mapStudent = distributeUserInviteService.getInviteRecord(saleIds, DateUtil.beginOfMonth(new Date()), new Date());
            for (Long saleId : saleIds) {
                List<DistributeUserInvite> distributeUserInvites = mapStudent.getOrDefault(saleId, List.of());
                Rankings ranking = Rankings.builder().id(saleId)
                        .sum(Math.toIntExact(distributeUserInvites.stream().map(DistributeUserInvite::getUserId).distinct().count())).build();
                ref.rankings.add(ranking);
            }
        }
        //按数量排序
        ref.rankings.sort(Comparator.comparing(Rankings::getSum).reversed());
        //取前三名
//        ref.rankings = ref.rankings.stream().filter(ranking -> ranking.getSum() > 0).limit(3).toList();
        //获取销售人员信息
        Map<Long, Optional<DistributeNodeInfo>> userIds = distributeNodeInfoService.getDistributeNodeInfo(ref.rankings
                .stream()
                .map(Rankings::getId)
                .toList());
        ref.rankings.forEach(ranking -> {
            Optional<DistributeNodeInfo> info = userIds.getOrDefault(ranking.getId(), Optional.empty());
            if (info.isPresent()) {
                ranking.setFullName(info.get().getFullName());
                ranking.setHeadImageUrl(info.get().getHeadImageUrl());
                ranking.setTypeName(info.get()
                        .getDistributeRoleCode()
                        .equals(DistributeSaleRoleEnum.ROLE_SLMB.getCode()) ? "推广员" : "团队成员");
                if (Objects.equals(ranking.getId(), distributeNodeInfo.getUserId())) {
                    ranking.setTypeName("我");
                }
            }
        });
        return ref.rankings;
    }

    /**
     * 员工列表查询实现
     */
    public List<EmployeeListItem> getEmployeeList(Long userId, String searchName) {
        DistributeNodeInfo distributeNodeInfo = distributeNodeInfoService.getNodeInfoForUser(userId, DistributeTypeEnum.TYPE_SALE);
        //获取销售人员
        List<DistributeNodeRoleChain> distributeNodeRoleChains = distributeNodeRoleChainDomainService
                .getAllSaleUserIdByRole(distributeNodeInfo.getId(), DistributeSaleRoleEnum.ROLE_DSPD_EMP.getCode());
        if (distributeNodeRoleChains.isEmpty()) {
            return new ArrayList<>();
        }
        //获取销售人员id
        List<Long> saleUserIds = distributeNodeRoleChains.stream().map(DistributeNodeRoleChain::getRefUserId).toList();
        //获取销售人员信息
        Map<Long, Optional<DistributeNodeInfo>> infoMap = distributeNodeInfoService.getDistributeNodeInfo(saleUserIds);
        List<EmployeeListItem> list;
        List<CompletableFuture<EmployeeListItem>> futures = new ArrayList<>();
        infoMap.forEach((saleUserId, info) -> {
            if (info.isEmpty()) {
                return;
            }
            //补充信息
            futures.add(CompletableFuture.supplyAsync(() -> createEmployeeListItem(info.get(), userId)));
        });
        CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).join();
        list = futures.stream().map(CompletableFuture::join).toList();
        return list.stream()
                .filter(employeeListItem -> StrUtil.isBlank(searchName) || employeeListItem.getName().contains(searchName))
                .toList();
    }

    private EmployeeListItem createEmployeeListItem(DistributeNodeInfo distributeNodeInfo, Long distributeUserId) {
        SaleAmountQuery saleAmountQuery = new SaleAmountQuery();
        saleAmountQuery.setSaleUserId(distributeNodeInfo.getUserId());
        saleAmountQuery.setDistributeUserId(distributeUserId);
        saleAmountQuery.setStartSaleTime(DateUtil.beginOfMonth(new Date()));
        saleAmountQuery.setEndSaleTime(new Date());
        //本月收益
        DistributeSale distributeSale = distributeOrderTaskSaleService.getSaleAmount(saleAmountQuery);
        return EmployeeListItem.builder()
                .id(distributeNodeInfo.getId())
                .name(distributeNodeInfo.getFullName())
                .headImageUrl(distributeNodeInfo.getHeadImageUrl())
                .mobile(distributeNodeInfo.getContactPhone())
                .monthlyPerformance(distributeSale.getAmount())
                .courseCount(Math.toIntExact(distributeSale.getCourseSum()))
                .distributorCount(Math.toIntExact(distributeSale.getMemberSum()))
                .status(String.valueOf(distributeNodeInfo.getEnableStatus()))
                .build();
    }
    // 推广员列表
    public PageResult<ExtensionOfficerListItem> getExtensionOfficerPage(MemberPageQuery memberPageQuery) {
        DistributeNodeInfo distributeNodeInfo = distributeNodeInfoService.getNodeInfoForUser(memberPageQuery.getDistributeUserId(), DistributeTypeEnum.TYPE_SALE);
            if (DistributeSaleRoleEnum.ROLE_DSPD_EMP.getCode().equals(distributeNodeInfo.getDistributeRoleCode())){
                try (Page<Object> page=PageHelper.startPage(memberPageQuery.getPage(),memberPageQuery.getSize())) {
                    List<DistributeUserInvite> list = distributeUserInviteService.getInviteRecordListByDistributeUserIdsAndRole(List.of(distributeNodeInfo.getUserId()), DistributeSaleRoleEnum.ROLE_SLMB.getCode(),null,null);
                    if (CollUtil.isNotEmpty(list)) {
                        //获取所有推广员id
                        List<Long> saleUserIds = list.stream().map(DistributeUserInvite::getUserId).toList();
                        //获取所有推广员信息
                        Map<Long, Optional<DistributeNodeInfo>> infoMap = distributeNodeInfoService.getDistributeNodeInfo(saleUserIds);
                        List<User> users =userRepository.getUserList(saleUserIds);
                        List<ExtensionOfficerListItem> extensionOfficerListItems = new ArrayList<>();
                        infoMap.forEach((saleUserId, info) -> {
                            if (info.isEmpty()) {
                                return;
                            }
                            String userAvatar = users.stream().filter(user -> user.getId().equals(saleUserId)).findFirst().map(User::getAvatar).orElse("");
                            //补充信息
                            extensionOfficerListItems.add(ExtensionOfficerListItem.builder()
                                    .id(info.get().getId())
                                    .headImageUrl(ObjectUtil.defaultIfNull(info.get().getHeadImageUrl(),userAvatar))
                                    .name(info.get().getFullName())
                                    .joinTime(new DateTime(info.get().getCreateTime()))
                                    .level("钻石会员")
                                    .build());
                        });
                        return PageResult.of((long) page.getTotal(), extensionOfficerListItems);
                    }
                }
            }else {
                DistributeNodeInfoQueryPage distributeNodeInfoQueryPage = new DistributeNodeInfoQueryPage();
                distributeNodeInfoQueryPage.setPage(memberPageQuery.getPage());
                distributeNodeInfoQueryPage.setSize(memberPageQuery.getSize());
                distributeNodeInfoQueryPage.setDistributeType(DistributeTypeEnum.TYPE_SALE.getType());
                distributeNodeInfoQueryPage.setDistributeRoleCode(DistributeSaleRoleEnum.ROLE_SLMB.getCode());
                distributeNodeInfoQueryPage.setUpLevelUserId(distributeNodeInfo.getUserId());
                distributeNodeInfoQueryPage.setFullName(memberPageQuery.getSearchName());
                PageResult<DistributeNodeInfoRespEntity> pageResult = distributeNodeInfoService.selectDistributeNodesByPage(distributeNodeInfoQueryPage);
                if (CollUtil.isNotEmpty(pageResult.getList())) {
                    //获取所有推广员id
                    List<Long> saleUserIds = pageResult.getList().stream().map(DistributeNodeInfoRespEntity::getUserId).toList();
                    //获取所有推广员信息
                    Map<Long, Optional<DistributeNodeInfo>> infoMap = distributeNodeInfoService.getDistributeNodeInfo(saleUserIds);
                    List<User> users =userRepository.getUserList(saleUserIds);
                    List<ExtensionOfficerListItem> extensionOfficerListItems = new ArrayList<>();
                    infoMap.forEach((saleUserId, info) -> {
                        if (info.isEmpty()) {
                            return;
                        }
                        String userAvatar = users.stream().filter(user -> user.getId().equals(saleUserId)).findFirst().map(User::getAvatar).orElse("");
                        //补充信息
                        extensionOfficerListItems.add(ExtensionOfficerListItem.builder()
                                .id(info.get().getId())
                                .headImageUrl(ObjectUtil.defaultIfNull(info.get().getHeadImageUrl(),userAvatar))
                                .name(info.get().getFullName())
                                .joinTime(new DateTime(info.get().getCreateTime()))
                                .level("钻石会员")
                                .build());
                    });
                    return PageResult.of((long) pageResult.getTotal(), extensionOfficerListItems);
                }
            }
        return PageResult.of(0L,List.of());
    }
    // 推广员列表
    public List<ExtensionOfficerListItem> getExtensionOfficerList(Long userId, String searchName) {
        DistributeNodeInfo distributeNodeInfo = distributeNodeInfoService.getNodeInfoForUser(userId, DistributeTypeEnum.TYPE_SALE);
        //获取所有推广员
        List<DistributeNodeRoleChain> distributeNodeRoleChains = distributeNodeRoleChainDomainService
                .getAllSaleUserIdByRole(distributeNodeInfo.getId(), DistributeSaleRoleEnum.ROLE_SLMB.getCode());
        if (distributeNodeRoleChains.isEmpty()) {
            return new ArrayList<>();
        }
        //获取所有推广员id
        List<Long> saleUserIds = distributeNodeRoleChains.stream().map(DistributeNodeRoleChain::getRefUserId).toList();
        //获取所有推广员信息
        Map<Long, Optional<DistributeNodeInfo>> infoMap = distributeNodeInfoService.getDistributeNodeInfo(saleUserIds);
        List<ExtensionOfficerListItem> extensionOfficerListItems = new ArrayList<>();
        infoMap.forEach((saleUserId, info) -> {
            if (info.isEmpty()) {
                return;
            }
            //补充信息
            extensionOfficerListItems.add(ExtensionOfficerListItem.builder()
                    .id(info.get().getId())
                    .headImageUrl(info.get().getHeadImageUrl())
                    .name(info.get().getFullName())
                    .joinTime(new DateTime(info.get().getCreateTime()))
                    .level("钻石会员")
                    .build());
        });
        return extensionOfficerListItems.stream()
                .filter(extensionOfficerListItem -> StrUtil.isBlank(searchName) || extensionOfficerListItem.getName()
                        .contains(searchName))
                .toList();
    }

    // 获取学生数据的方法
    public PageResult<StudentData> getStudentsDataForNodeUser(Long userId,StudentPageQuery studentPageQuery) {
        DistributeUserInvitePageQuery  distributeUserInvitePageQuery = new DistributeUserInvitePageQuery();
        distributeUserInvitePageQuery.setDistributeUserId(userId);
        distributeUserInvitePageQuery.setPage(studentPageQuery.getPage()== null?1:studentPageQuery.getPage());
        distributeUserInvitePageQuery.setSize(studentPageQuery.getSize()== null?10:studentPageQuery.getSize());
        distributeUserInvitePageQuery.setIncludeLowLevel(1);
        List<Long> chainUserIds=new ArrayList<>();
        chainUserIds.add(userId);
        DistributeNodeInfo distributeNodeInfo=distributeNodeInfoService.getOne(Wrappers.lambdaQuery(DistributeNodeInfo.class)
                .eq(DistributeNodeInfo::getDistributeType, DistributeTypeEnum.TYPE_SALE.getType())
                .eq(DistributeNodeInfo::getUserId, userId)
                .eq(DistributeNodeInfo::getDataStatus, DistributeDataStatusEnum.STATUS_CURT.getStatus())
        );
        if (distributeNodeInfo != null) {
            if (distributeUserInvitePageQuery.getDistributeUserId()!=null&&distributeUserInvitePageQuery.getIncludeLowLevel()!=null&&distributeUserInvitePageQuery.getIncludeLowLevel()==1){
                Map<Long,Set<Long>> lowNodeUserIdMap=distributeNodeRoleChainDomainService.getLowNodeUserIds(DistributeTypeEnum.TYPE_SALE.getType(), List.of(distributeUserInvitePageQuery.getDistributeUserId()), distributeNodeInfo.getDistributeRoleCode());
                lowNodeUserIdMap.values().forEach(chainUserIds::addAll);
            }
            distributeUserInvitePageQuery.setDistributeChainUserIds(chainUserIds);
            distributeUserInvitePageQuery.setSearchValue( studentPageQuery.getSearchName());
            PageResult<DistributeUserInviteVo>  distributeUserInvitePage =distributeUserInviteService.queryDistributeUserInvitePage( distributeUserInvitePageQuery);
            if (CollUtil.isNotEmpty(distributeUserInvitePage.getList())) {
                //获取学员信息
                List<User> users = userRepository.getUserList(distributeUserInvitePage.getList().stream()
                        .map(DistributeUserInviteVo::getUserId)
                        .toList());
                List<StudentData> studentData= fillStudentUsersByDistributeNode(users, distributeNodeInfo);
                return PageResult.of((long) distributeUserInvitePage.getTotal(),studentData);
            }
        }
        return PageResult.of(0L,List.of());

    }
    private List<StudentData> fillStudentUsersByDistributeNode(List<User> users,DistributeNodeInfo distributeNodeInfo) {
        List<StudentData> students;
        List<CompletableFuture<StudentData>> completableFutures = users.stream()
                .map(user -> CompletableFuture.supplyAsync(() -> {
                    StudentData studentData = new StudentData();
                    studentData.setId(user.getId());

                    studentData.setHeadImageUrl(user.getAvatar());
                    studentData.setName(user.getName());
                    //手机号脱敏
                    studentData.setPhone(DesensitizedUtil.mobilePhone(user.getPhone()));
                    SaleAmountQuery saleAmountQuery = new SaleAmountQuery();
                    saleAmountQuery.setPayUserId(user.getId());
                    if (distributeNodeInfo.getDistributeRoleCode()!=null&&DistributeSaleRoleEnum.ROLE_DSPD_EMP.getCode().equals(distributeNodeInfo.getDistributeRoleCode())){
                        saleAmountQuery.setSaleUserId(distributeNodeInfo.getUserId());
                        saleAmountQuery.setDistributeUserId(distributeNodeInfo.getAdminUserId());
                    }else {
                        saleAmountQuery.setDistributeUserId(distributeNodeInfo.getUserId());
                    }
                    saleAmountQuery.setPayUserId(user.getId());
                    DistributeSale distributeSale = distributeOrderTaskSaleService.getSaleAmount(saleAmountQuery);
                    //总消费
                    studentData.setTotalConsumption(distributeSale.getOrderAmount());
                    //月度消费
                    saleAmountQuery = new SaleAmountQuery();
                    saleAmountQuery.setPayUserId(user.getId());
                    saleAmountQuery.setDistributeUserId(distributeNodeInfo.getUserId());
                    if (distributeNodeInfo.getDistributeRoleCode()!=null&&DistributeSaleRoleEnum.ROLE_DSPD_EMP.getCode().equals(distributeNodeInfo.getDistributeRoleCode())){
                        saleAmountQuery.setSaleUserId(distributeNodeInfo.getUserId());
                        saleAmountQuery.setDistributeUserId(distributeNodeInfo.getAdminUserId());
                    }else {
                        saleAmountQuery.setDistributeUserId(distributeNodeInfo.getUserId());
                    }
                    saleAmountQuery.setStartSaleTime(DateUtil.beginOfMonth(new Date()));
                    saleAmountQuery.setEndSaleTime(new Date());
                    distributeSale = distributeOrderTaskSaleService.getSaleAmount(saleAmountQuery);
                    studentData.setMonthlyConsumption(distributeSale.getOrderAmount());
                    return studentData;
                }))
                .toList();
        CompletableFuture.allOf(completableFutures.toArray(new CompletableFuture[0])).join();
        students = completableFutures.stream().map(CompletableFuture::join).toList();
        return students;
    }
    // 获取学生数据的方法
    public List<StudentData> getStudentsData(long userId, String searchName) {
        DistributeNodeInfo distributeNodeInfo = distributeNodeInfoService.getNodeInfoForUser(userId, DistributeTypeEnum.TYPE_SALE);
        if (distributeNodeInfo == null) {
            return List.of();
        }
        //获取所有销售
        List<DistributeNodeRoleChain> sale = distributeNodeRoleChainDomainService.getAllSaleNodeId(distributeNodeInfo.getId());
        List<Long> userIds = new ArrayList<>();
        for (DistributeNodeRoleChain distributeNodeRoleChain : sale) {
            userIds.add(distributeNodeRoleChain.getRefUserId());
        }
        userIds.add(userId);
        //获取邀请的学员
        List<DistributeUserInvite> studentsInvite = distributeUserInviteService.getInviteRecordListByDistributeUserId(userIds);
        List<Long> memberId = sale.stream().filter(distributeNodeRoleChain -> distributeNodeRoleChain
                .getRefRoleCode().equals(DistributeSaleRoleEnum.ROLE_SLMB.getCode())).map(DistributeNodeRoleChain::getRefUserId).toList();
        //排除会员
        studentsInvite = studentsInvite.stream()
                .filter(distributeUserInvite -> !memberId.contains(distributeUserInvite.getUserId()))
                .toList();
        //获取学员信息
        List<User> users = userRepository.getUserList(studentsInvite.stream()
                .map(DistributeUserInvite::getUserId)
                .toList());
        List<StudentData> students;
        List<CompletableFuture<StudentData>> completableFutures = users.stream()
                .map(user -> CompletableFuture.supplyAsync(() -> {
                    StudentData studentData = new StudentData();
                    studentData.setId(user.getId());
                    studentData.setHeadImageUrl(user.getAvatar());
                    studentData.setName(user.getName());
                    //手机号脱敏
                    studentData.setPhone(DesensitizedUtil.mobilePhone(user.getPhone()));
                    SaleAmountQuery saleAmountQuery = new SaleAmountQuery();
                    saleAmountQuery.setDistributeUserId(userId);
                    saleAmountQuery.setPayUserId(user.getId());
                    DistributeSale distributeSale = distributeOrderTaskSaleService.getSaleAmount(saleAmountQuery);
                    //总消费
                    studentData.setTotalConsumption(distributeSale.getOrderAmount());
                    //月度消费
                    saleAmountQuery = new SaleAmountQuery();
                    saleAmountQuery.setDistributeUserId(userId);
                    saleAmountQuery.setPayUserId(user.getId());
                    saleAmountQuery.setStartSaleTime(DateUtil.beginOfMonth(new Date()));
                    saleAmountQuery.setEndSaleTime(new Date());
                    distributeSale = distributeOrderTaskSaleService.getSaleAmount(saleAmountQuery);
                    studentData.setMonthlyConsumption(distributeSale.getOrderAmount());
                    return studentData;
                }))
                .toList();
        CompletableFuture.allOf(completableFutures.toArray(new CompletableFuture[0])).join();
        students = completableFutures.stream().map(CompletableFuture::join).toList();
        //按名称过滤
        return students.stream()
                .filter(studentData -> StrUtil.isBlank(searchName) || studentData.getName().contains(searchName))
                .toList();
    }
    // 获取订单数据的方法
    public PageResult<DistributorOrder> getOrderPage(Long userId, OrderPageQuery orderQuery) {
        if (userId!=null){
            DistributeNodeRoleChainExistModel existModel=distributeNodeRoleChainExistLoader.loadModelByUserId(userId, DistributeTypeEnum.TYPE_SALE.getType());
            try (Page<Object> page=PageHelper.startPage(orderQuery.getPage(), orderQuery.getSize())){
                List<DistributeUserProfitDetailVo>  userProfitDetailVos=null;
                List<DistributorOrder> list=List.of();
                DistributeUserSaleDetailQuery distributeUserSaleDetailQuery=new DistributeUserSaleDetailQuery();
                distributeUserSaleDetailQuery.setDistributeUserId(userId);
                if (StrUtil.isNotBlank( orderQuery.getStartOrderTime())){
                    distributeUserSaleDetailQuery.setStartDistributeTime(DateUtil.parseTime(orderQuery.getStartOrderTime()));
                }
                if (StrUtil.isNotBlank( orderQuery.getEndOrderTime())){
                    distributeUserSaleDetailQuery.setEndDistributeTime(DateUtil.parseTime(orderQuery.getEndOrderTime()));
                }
                if (existModel.getDistributeNodeInfo().getDistributeRoleCode().equals(DistributeSaleRoleEnum.ROLE_DSPD_EMP.getCode())){
                    distributeUserSaleDetailQuery.setUpLevelUserId(existModel.getUpLevelNodeInfo().getUserId());
                     userProfitDetailVos=distributeOrderTaskSaleService.getDistributeEmployeeContributeDetailList(distributeUserSaleDetailQuery);
                }else {
                     userProfitDetailVos=distributeOrderTaskSaleService.getDistributeUserProfitDetailList(distributeUserSaleDetailQuery);
                }
                if (CollUtil.isNotEmpty( userProfitDetailVos)){
                    OrderQueryPage queryPage = new OrderQueryPage();
                    queryPage.setOrdersId(userProfitDetailVos.stream().map(a->Long.parseLong(a.getOrderId())).toList());
                    List<OrderList> orderList = iOrderRepository.getOrderList(queryPage);
                    Map<Long, Optional<OrderList>> mapOrder = orderList.stream()
                            .collect(Collectors.groupingBy(OrderList::getOrderId, Collectors.reducing((a, b) -> b)));
                    list= userProfitDetailVos.stream()
                            .map(item -> {
                                DistributorOrder order = new DistributorOrder();
                                order.setBenefitAmount(item.getDistributeAmount());
                                order.setSettlementStatus("2");
                                Optional<OrderList> optionalOrderList = mapOrder.getOrDefault(Long.parseLong(item.getOrderId()), Optional.empty());
                                if (optionalOrderList.isEmpty()) {
                                    return order;
                                }
                                order.setOrderId(optionalOrderList.get().getOrderId());
                                order.setPaymentAmount(optionalOrderList.get().getTotalAmount());
                                order.setProductName(optionalOrderList.get().getProductName());
                                order.setUserName(optionalOrderList.get().getName());
                                order.setPayTime(optionalOrderList.get().getPayTime());
                                order.setOrderTime(optionalOrderList.get().getOrderTime());
                                return order;

                            })
                            .toList();

                }
                return PageResult.of(page.getTotal(), list);
            }

        }
        return PageResult.of(0L,List.of());

    }
    // 获取订单数据的方法
    public List<DistributorOrder> getOrderList(Long userId, OrderQuery orderQuery) {
        List<DistributorOrder> orders = new ArrayList<>();
        SaleAmountQuery saleAmountQuery = new SaleAmountQuery();
        saleAmountQuery.setDistributeUserId(userId);
        if (StrUtil.isNotBlank(orderQuery.getStartOrderTime())) {
            saleAmountQuery.setStartSaleTime(new DateTime(orderQuery.getStartOrderTime()));
        }
        if (StrUtil.isNotBlank(orderQuery.getEndOrderTime())) {
            saleAmountQuery.setEndSaleTime(new DateTime(orderQuery.getEndOrderTime()));
        }
        saleAmountQuery.setPayUserId(orderQuery.getPayUserId());
        if (orderQuery.getSettlementStatus() != null) {
            if (orderQuery.getSettlementStatus() == 0) {
                saleAmountQuery.setStatus(List.of("0", "1", "2"));
            } else {
                saleAmountQuery.setStatus(List.of("3"));
            }
        }
        saleAmountQuery.setSaleUserId(orderQuery.getSaleUserId());
        List<DistributeOrder> distributeOrders = distributeOrderTaskSaleService.getSaleOrder(saleAmountQuery);
        if (distributeOrders.isEmpty()) {
            return orders;
        }
        OrderQueryPage queryPage = new OrderQueryPage();
        queryPage.setOrdersId(distributeOrders.stream().map(DistributeOrder::getOrderId).toList());
        List<OrderList> orderList = iOrderRepository.getOrderList(queryPage);
        Map<Long, Optional<OrderList>> mapOrder = orderList.stream()
                .collect(Collectors.groupingBy(OrderList::getOrderId, Collectors.reducing((a, b) -> b)));
        return distributeOrders.stream().map(item -> {
            DistributorOrder order = new DistributorOrder();
            order.setOrderId(item.getOrderId());
            order.setBenefitAmount(item.getDistributeSaleAmount());
            order.setSettlementStatus(item.getDistributeOrderStatus());
            Optional<OrderList> optionalOrderList = mapOrder.getOrDefault(item.getOrderId(), Optional.empty());
            if (optionalOrderList.isEmpty()) {
                return order;
            }
            order.setPaymentAmount(optionalOrderList.get().getTotalAmount());
            order.setProductName(optionalOrderList.get().getProductName());
            order.setUserName(optionalOrderList.get().getName());
            order.setPayTime(optionalOrderList.get().getPayTime());
            order.setOrderTime(optionalOrderList.get().getOrderTime());
            return order;
        }).toList();
    }

    // 获取订单统计信息
    public DistributorOrderStatistics getOrderStatistics(Long userId) {
        SaleAmountQuery saleAmountQuery = new SaleAmountQuery();
        saleAmountQuery.setDistributeUserId(userId);
        //总收益
        CompletableFuture<DistributeSale> totalBenefit = CompletableFuture
                .supplyAsync(() -> distributeOrderTaskSaleService.getSaleAmount(saleAmountQuery));
        //已结算金额
        SaleAmountQuery settledAmountQuery = new SaleAmountQuery();
        settledAmountQuery.setDistributeUserId(userId);
        settledAmountQuery.setStatus(List.of("3"));
        CompletableFuture<DistributeSale> settledAmount = CompletableFuture
                .supplyAsync(() -> distributeOrderTaskSaleService.getSaleAmount(settledAmountQuery));
        //待结算金额
        SaleAmountQuery pendingAmountQuery = new SaleAmountQuery();
        pendingAmountQuery.setDistributeUserId(userId);
        pendingAmountQuery.setStatus(List.of("1", "2"));
        CompletableFuture<DistributeSale> pendingAmount = CompletableFuture
                .supplyAsync(() -> distributeOrderTaskSaleService.getSaleAmount(saleAmountQuery));
        return DistributorOrderStatistics.builder()
                .totalBenefit(totalBenefit.join().getAmount())
                .pendingAmount(pendingAmount.join().getAmount())
                .settledAmount(settledAmount.join().getAmount())
                .build();
    }

    // 加盟商资料更新方法
    public void updateProfile(Long userId, String headImageUrl, String fullName, DistributeSaleRoleEnum role) {
        distributeNodeInfoService.updateProfile(userId, headImageUrl, fullName,  role);
    }

    // 加盟商员工状态更新方法
    public void updateEmployeeStatus(Long id, Integer status) {
        DistributeNodeInfo distributeNodeInfo=distributeNodeInfoService.getById(id);
        if (distributeNodeInfo!=null&&DistributeSaleRoleEnum.ROLE_DSPD_EMP.getCode().equals(distributeNodeInfo.getDistributeRoleCode())){
            DistributeNodeInfoStateReq distributeNodeInfoStateReq = new DistributeNodeInfoStateReq();
            distributeNodeInfoStateReq.setUserId(distributeNodeInfo.getUserId());
            distributeNodeInfoStateReq.setEnableStatus(status);
            distributeNodeInfoStateReq.setDistributeType(DistributeTypeEnum.TYPE_SALE.getType());
            platformUserArchBI.updateNodeState(distributeNodeInfoStateReq);
        }
    }
}
